package com.mbigger.admin.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.mbigger.admin.beans.PageQuery;
import com.mbigger.admin.beans.PageResult;
import com.mbigger.admin.common.RequestHolder;
import com.mbigger.admin.dao.UserMapper;
import com.mbigger.admin.entity.User;
import com.mbigger.admin.exception.ParamException;
import com.mbigger.admin.param.UserParam;
import com.mbigger.admin.service.UserService;
import com.mbigger.admin.util.BeanValidator;
import com.mbigger.admin.util.IpUtil;
import com.mbigger.admin.util.MD5Util;
import com.mbigger.admin.util.PasswordUtil;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;

	/**
	 * 新建用户
	 * 
	 * @param param
	 */
	public void save(UserParam param) {
		BeanValidator.check(param);
		if (checkTelephoneExist(param.getTelephone(), param.getId())) {
			throw new ParamException("电话已被占用");
		}
		if (checkEmailExist(param.getMail(), param.getId())) {
			throw new ParamException("邮箱已被占用");
		}

		String password = PasswordUtil.randomPassword();

		String encryptedPassword = MD5Util.encrypt(password);
		User user = User.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
				.password(encryptedPassword).deptId(param.getDeptId()).status(param.getStatus())
				.remark(param.getRemark()).build();
		user.setOperator(RequestHolder.getCurrentUser().getUsername());
		user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
		user.setOperateTime(new Date());

		userMapper.insert(user);
	}

	/**
	 * 更新用户
	 * 
	 * @param param
	 */
	public void update(UserParam param) {
		BeanValidator.check(param);
		if (checkTelephoneExist(param.getTelephone(), param.getId())) {
			throw new ParamException("电话已被占用");
		}
		if (checkEmailExist(param.getMail(), param.getId())) {
			throw new ParamException("邮箱已被占用");
		}

		User before = userMapper.selectById(param.getId());
		Preconditions.checkNotNull(before, "待更新的用户不存在");
		User after = User.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
				.deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
		after.setOperator(RequestHolder.getCurrentUser().getUsername());
		after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
		after.setOperateTime(new Date());
		System.err.println(after);
		userMapper.updateById(after);
	}

	/**
	 * 部门用户列表，分页
	 * 
	 * @param deptId
	 * @param page
	 * @return
	 */
	public PageResult<User> getPageByDeptId(int deptId, PageQuery page) {
		BeanValidator.check(page);
		int count = userMapper.countByDeptId(deptId);
		if (count > 0) {
			List<User> list = userMapper.getPageByDeptId(deptId, page);
			return PageResult.<User>builder().total(count).data(list).build();
		}
		return PageResult.<User>builder().build();
	}

	/**
	 * 获取所有用户
	 * 
	 * @return
	 */
	public List<User> getAll() {
		return userMapper.getAll();
	}
	
	public User selectById( Integer userId) {
		return userMapper.selectById(userId);
	}

	private boolean checkEmailExist(String mail, Integer userId) {
		return userMapper.countByMail(mail, userId) > 0;
	}

	private boolean checkTelephoneExist(String telephone, Integer userId) {
		return userMapper.countByTelephone(telephone, userId) > 0;
	}

	public User findByKeyword(String keyword) {
		return userMapper.findByKeyword(keyword);
	}

}
